package com.tools.utils.markdown;

import org.springframework.util.ObjectUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author LY
 * @create 2023/9/6 9:52
 * @Description md模板转sql语句
 * sql模板格式：
 * ## 表名：cms_sys_user
 *
 * |     列名      |   数据类型   | 长度  | 主键  | 是否非空 |  备注  |
 * |:-----------:|:--------:|:---:|:---:|:----:|:----:|
 * |     id      |   int    | 11  |  是  |  是   | 主键id |
 * |    name     | varchar  | 20  |  否  |  否   |  名称  |
 * |     sex     |   char   |  1  |  否  |  是   |  性别  |
 * | class_grade | varchar  | 10  |  否  |  是   |  班级  |
 * | create_time | datetime |     |  否  |  是   | 创建时间 |
 * |  create_by  | varchar  | 10  |  否  |  是   | 创建人  |
 * | update_time | datetime |     |  否  |  是   | 更新时间 |
 * |  update_by  | varchar  | 10  |  否  |  是   | 更新人  |
 */
public class SqlMD {

    private static final String ENCODING = "utf-8";

    public static void main(String[] args) {
        new SqlMD().readMD();
    }

    public void test(){
        /*测试读取文件地址*/
        System.out.println(this.getClass().getResource("/").getFile());
        System.out.println("sql.md");
        File file = new File(this.getClass().getResource("/sql.md").getFile());
        System.out.println(file.exists());
        System.out.println(this.getClass().getResource("/sql.md").getFile());
    }

    /**
     * 文件读取
     */
    public void readMD(){
        String filePath = this.getClass().getResource("/sql.md").getFile();
        InputStreamReader read = null;
        BufferedReader bufferedReader = null;
        List<String> list = new ArrayList<>();
        try {
            read = new InputStreamReader(new FileInputStream(filePath),ENCODING);
            bufferedReader = new BufferedReader(read);
            String lineTXT = null;
            int line = 1;
            int row = 0;
            while ((lineTXT = bufferedReader.readLine()) != null) {
                System.out.println("第" + line + "行：" + lineTXT);
                row = lineTXT.contains("表名：") ? line : row;// 去除md模板和sql语句无关行，如：|     列名      |   数据类型   | 长度  | 主键  | 是否非空 |  备注  |
                if (!ObjectUtils.isEmpty(lineTXT.trim()) && line != (row+1) && line != (row+2) && line != (row+3)){
                    list.add(lineTXT.trim());
                }
                line++;
            }
            bufferedReader.close();
            read.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list.size() > 0){
            convertToSql(list);
        }
    }

    /**
     * 生成sql语句
     */
    public void convertToSql(List<String> list){
        StringBuilder sbr = new StringBuilder();
        String primary = null;
        for (int i = 0; i < list.size(); i++) {
            String row = list.get(i);
            if (row.contains("表名：")){
                if (!ObjectUtils.isEmpty(sbr)){
                    if (!ObjectUtils.isEmpty(primary)){
                        sbr.append("\t" + primary + "\n");
                    }
                    sbr.append(")ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n");
                }
                primary = null;//清空进入下一个sql语句
                sbr.append("CREATE TABLE " + row.substring(row.indexOf("表名：")+3) + "(\n");
            }else {
                row = row.substring(1,row.length()-1);
                String[] column = row.split("\\|");
                String train0 = column[0].trim();
                String train1 = column[1].trim().toUpperCase();
                String train2 = column[2].trim();
                String train3 = column[3].trim();
                String train4 = column[4].trim();
                String train5 = column[5].trim();
                String append = train0 + " " + train1;
                // 处理主键
                if (train3.equals("是")){
                    append += "(" + train2 + ") NOT NULL AUTO_INCREMENT";
                    primary = "PRIMARY KEY (`" + train0 + "`)";
                }else {
                    if (!ObjectUtils.isEmpty(train2)){
                        append += "(" + train2 + ")";
                    }
                    if (train4.equals("是")){
                        append += " NOT NULL";
                    }else if (train4.equals("否")){
                        append += " DEFAULT NULL";
                    }
                    append += " COMMENT '" + train5 + "'";
                }
                sbr.append("\t" + append + ",\n");
            }
        }
        if (!ObjectUtils.isEmpty(primary)){
            sbr.append("\t" + primary + "\n");
        }
        sbr.append(")ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
        System.out.println(sbr);
    }
}
